<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Autorization extends Controller {

	//protected $_data;
	public function before()
	{
		parent::before();
		//$this->r = RedisDB::instance();
	    $this->a2 = A2::instance('a2');
		$this->a1 = $this->a2->a1;
		$this->user = $this->a2->get_user();
/*
		$this->acl1 = new Zend_Acl;
		$this->acl1->addRole(new Zend_Acl_Role('owner'));
		$this->acl1->addRole(new Zend_Acl_Role('user'));
		$this->acl1->addRole(new Zend_Acl_Role('guest'));
		$this->acl1->add(new Zend_Acl_Resource('blog'));
*/
		//$this->acl2->add_role('owner');
		//$this->acl2->add_role('user');
		//$this->acl2->add_role('guest');
		//$this->acl2->add_resource('blog');
		//$s2 = serialize($this->acl2->roles);
		//print_r($this->acl2);
        //exit($s2);
		if ($this->request->action() != 'login' AND !$this->user)
		{			//echo 'not logged in';
			$this->redirect('login');		}
		elseif ($this->user)
		{			//echo 'logged in';
			$this->get_data();
			//$this->set_acl();		}
	}

	public function after()
	{
		//Debug::vars($this->_data['interfaces']);
		//print_r($this->_data['interfaces']);
		parent::after();
	}

	private function get_data()
	{        $this->_data['interfaces'] = array();
		foreach(Kohana::modules() as $k=>$v)
		{
			if (strpos($v, MODPATH.'01_') !== FALSE)
			{
				$this->_data['interfaces'][$k] = Kohana::$config->load('interface_'.$k)->as_array();
			}
		}

		foreach($this->_data['interfaces'] as $k=>&$v)
		{			if (!empty($v['ext_links']))
			{
				foreach($v['ext_links'] as $k2=>&$v2)
				{
					$this->_data['interfaces'][$k2]['links'] = array_merge($this->_data['interfaces'][$k2]['links'],$v['ext_links'][$k2]['links']);				}
				unset($v['ext_links']);			}		}

        //print_r($this->_data['interfaces']);
		$this->_data['controller'] = $this->request->controller();
		$this->_data['action'] = $this->request->action();
		$this->_data['type'] = $this->request->param('type','full');
		$this->_data['id'] = $this->request->param('id',NULL);
		//$this->_data['do'] = $this->request->param('do',NULL);
/*
		if ($this->a2->allowed('attach','delete'))
		{
			$this->_data['type'] = 'attach';
		}
		else if ($this->a2->allowed('transport','delete'))
		{
			$this->_data['type'] = 'transport';
		}
		else if ($this->a2->allowed('employee','delete'))
		{
			$this->_data['type'] = 'employee';
		}
		else
		{
			$this->_data['type'] = 'attach';
		}
*/
        $this->_data['client_id'] = Kohana::$config->load('client')->client_id;
		$this->_data['username'] = $this->user->username;
		//$this->_data['roles'] = $this->get_role_id();
		//$this->_data['location'] = $this->user->id_location;
/*
		$this->_data['location'] = DB::select()
			->from('location')
			->where('id', '=', $this->user->id_location)
			->limit(1)
			->execute()
			->get('location');
*/
        if ( Request::current()->method() != Request::POST AND !$this->request->is_ajax() AND $this->_data['controller'] != 'autorization')
        {
			//$this->user->last_uri = URL::site($this->request->uri());
			//$this->r->set('users:'.$this->user->id,json_encode(get_object_vars($this->user)));
			//$user = json_decode($this->r->get('users:'.$id));
			//$this->user->last_uri = URL::site($this->request->uri());
			//$this->user->save();		}


		//return $obj->rules;
		//$this->r->select(7);
	}

    private function set_acl()
    {
		$this->acl = new ACL;
        //$groups = $this->r->hGetAll('groups:lookup:groupname');
		//print_r($groups);
		//exit;
		$this->acl->add_role('guest');
		foreach($this->r->hGetAll('groups:lookup:groupname') as $group=>$id)
		{
			$this->acl->add_role($group,array('guest'));
		}

		foreach($this->_data['interfaces'] as &$module)
		{
			foreach($module['links'] as $res=>&$link)
			{
				//$res = key($link);
				if ($res != '#')
				{
					$this->acl->add_resource($res);
				}
			}
		}
		$groups = $this->r->sMembers('user_groups:'.$this->user->id);
		foreach($groups as &$group)
		{
			$obj = json_decode($this->r->get('groups:'.$group));
			foreach($obj->rules as $res=>&$rule)
			{				if ($rule & 1 << 0)
				{					$allow[] = 'read';
				}
				if ($rule & 1 << 1)
				{
					$allow[] = 'edit';
				}
				if ($rule & 1 << 2)
				{
					$allow[] = 'create';
				}
				if (is_array($allow))
				{					$this->acl->allow($obj->id,$res,$allow);
					//echo $rule.': '.$obj->id.' '.$res. ': '.implode(',',$allow).'<br />';
					unset($allow);				}
			}
		}
    }
/*
	public function body()
	{
 		if ($this->is_allowed($this->r->sMembers('user_groups:'.$this->user->id),'read'))
 		{
 			$body = View::factory($this->_data['controller'].'/'.$this->_data['action'],$this->_data);
 		}
 		else
 		{
 			$body = View::factory('page/bootstrap_denied');
 		}
 		$header = View::factory('page/bootstrap_header',$this->_data);
		$footer = View::factory('page/bootstrap_footer',$this->_data);
		$this->response->body($header.$body.$footer);
	}
*/
	public function action_login()
	{
		if($this->user) //cannot create new accounts when a user is logged in
		{
			$this->redirect('/');
			//$this->redirect(!empty($this->user->last_uri)?$this->user->last_uri:$this->_data['type']);
		}
        elseif (!empty($_POST))
        {
			$post = Validation::factory($this->request->post())
				->rule('username', 'not_empty')
				->rule('username', 'min_length', array(':value', 3))
				->rule('username', 'max_length', array(':value', 32))
				->rule('username', 'regex', array(':value', '/^[0-9a-z_.-]++$/iD'))
				->rule('password', 'not_empty')
				->rule('password', 'min_length', array(':value', 4))
				->rule('password', 'max_length', array(':value', 32));
            //echo 'check'.$this->a1->login($post['username'],$post['password'],FALSE);
			if($post->check() AND $this->a1->login($post['username'],$post['password'],FALSE))
			{
				$this->user = $this->a2->get_user();
				//$this->user->last_login = time();
				//$this->user->logins += 1;
				//$this->r->set('users:'.$this->user->id,json_encode(get_object_vars($this->user)));
				//$this->get_data();
				/*
				$query = DB::insert('user_logs',array('user_id', 'time', 'action'))
					->values(array($this->user->id, $this->user->last_login, 'вошел'))
					->execute();
				*/
				//$this->request->redirect(!empty($this->user->last_uri)?$this->user->last_uri:'docs');
				$this->redirect('/');
			}
        }

        $this->response->body(View::factory('login'));
	}

	public function action_logout()
	{
		/*
		$this->user = $this->a2->get_user();
		$time=time();
		$query = DB::insert('user_logs',array('user_id', 'time', 'action'))
			->values(array($this->user->id, $time, 'вышел'))
			->execute();
		*/
		$this->a1->logout();
		$this->user = NULL;
		$this->redirect('login');
	}

	public function get_role_id()
	{        $roles = array();
        // We need to explicitly call find_all() to get the roles. Lazy loading...
/*
        $my_roles = $this->roles->find_all();
        foreach ($my_roles as $role)
        {
            // Now grab the names of the roles. Used on the ACL module
            $roles[] = $role->name;
        }
*/
        return $roles;	}
/*
	public function action_denied()
	{		$header = View::factory('page/bootstrap_header',$this->_data);
		$body = View::factory('page/bootstrap_denied');
		$footer = View::factory('page/bootstrap_footer',$this->_data);
		$this->response->body($header.$body.$footer);	}
*/
/*
	public function action_create()
	{
	    if($this->user) //cannot create new accounts when a user is logged in
		{
			//$this->action_index();
		}
        if (!empty($_POST))
        {
			$user = ORM::factory('user')
				->values($_POST);

			if ($user->check())
			{
			    // Saving login role and the one coming from dropdown menu
        	    $user->save();
       		    $user->add('roles', ORM::factory('role', array('name' => 'login')));
        	    $user->add('roles', ORM::factory('role', array('id' => $_POST['role'])));

				// user  created, show login form
				//$this->action_login();
			}
		}
		else
		{
		    //show form
            echo form::open();
            echo 'username:' . form::input('username') . '<br />';
            echo 'password:' . form::password('password') . '<br />';
            echo 'password confirm:' . form::password('password_confirm') . '<br />';
            echo 'email:' . form::input('email') . '<br />';
            echo 'role:' . form::select('role',array('3'=>'author','2'=>'admin')) . '<br />';
            echo form::submit('create','create');
            echo form::close();
		}
	}
*/

	public function action_index()
	{
        //$this->redirect(!empty($this->user->last_uri)?$this->user->last_uri:'docs');
        $this->response->body('index');
		//print_r($this->a2->_roles);
		//exit();
		//$header = View::factory('page/header',$this->_data);
		//$body = View::factory('page/body_'.$this->_data['type'],$this->_data);
		//$footer = View::factory('page/footer');
		//$this->response->body($header.$body.$footer);
	}
/*
	public function is_allowed($groups,$level)
	{		if ($this->user->id == 1)
		{			return TRUE;		}
		foreach($groups as &$group)
		{			$uri = $this->_data['controller'].($this->_data['action']=='index'?'':'/'.$this->_data['action']);
			if ($this->acl->is_allowed($group,$uri,$level))
			{				return TRUE;
			}		}
		return FALSE;	}
*/
} // End Autorization